<template>
  <div class="container">
    <table>
      <thead>
        <tr>
          <!-- 表头 -->
          <th v-for="item in tableHead" :key="item">{{ item }}</th>
        </tr>
      </thead>
      <tbody>
        <!-- 数据 -->
        <tr v-for="item in data" :key="item.id">
          <td
            v-for="(value, key) in item"
            :key="key"
            :class="{ active: key === 'price' && value > 100 }"
          >
            {{ value }}
          </td>
          <td>
            <a href="" @click.prevent="onDelete(item.id)">删除</a>
          </td>
        </tr>
        <!-- 统计 -->
        <tr>
          <td>统计:</td>
          <td colspan="2">总价钱: {{ total }}</td>
          <td colspan="2">平均价: {{ avg }}</td>
        </tr>
      </tbody>
    </table>
    <input v-model="currentName" placeholder="资产名称" type="text">
    <input v-model.number="currentPrice" type="text">
    <button @click="onAdd">添加资产</button>
  </div>
</template>

<script>
import moment from 'moment';

let idCounter = 0;
export default {
  data () {
    return {
      currentName: '',
      currentPrice: 0,
      tableHead: ['编号', '资产名称', '价格', '创建时间', '操作'],
      data: [],
    };
  },
  methods: {
    onAdd () {
      this.data.push({
        id: idCounter++,
        name: this.currentName,
        price: this.currentPrice,
        createTime: moment().format('YYYY-MM-DD'),
      });
    },
    onDelete (id) {
      this.data = this.data.filter(d => d.id !== id);
    },
  },
  computed: {
    // 总价
    total () {
      return this.data.reduce((prev, current) => prev + current.price, 0);
    },
    // 平均价
    avg () {
      // return this.total / (this.data.length || 1);
      return this.total && this.total / this.data.length;
    },
  },
}
</script>

<style scoped>
table td.active {
  color: red;
}
</style>